//==============================================================================
//
//  Name: VirtualLCD_Log.c
//  Copyright: Dave Perrow
//  Author: Dave Perrow
//  Date: 09/07/11 18:09
//  Description: Code to log data to a file in the displays directory
// 
//==============================================================================
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <windows.h>
#include <wingdi.h>
#include "VirtualLCD.h"
#include "VirtualLCDwm.h"

extern int __stdcall mylog(char * module, char * msg);
extern int __stdcall open_mylog();

static FILE *fp_log = NULL;
static int debug;
static int log_opened=0;
static int my_window_x,my_window_y,my_window_width,my_window_height;
static int DontShowWindow,Record,RecordInterval;
char RecordFile[256];

SCREENDEF Lines[4];
//
// Functions to return some global values
//

extern int __stdcall pDontShowWindow(void) { return DontShowWindow; }
extern int __stdcall pRecord(void) { return Record; }
extern int __stdcall pRecordInterval(void) { return RecordInterval; }
extern char * __stdcall pRecordFile(void) { return RecordFile; }


//================================================================================================================================
// function to copy a string and set the first newline character to 0
//================================================================================================================================
extern void __stdcall strcpytonl(char *so, char *si)
{ int i;
  for (i=0; i<strlen(si); i++) { if (si[i]=='\n') { so[i]=0; break; } else so[i]=si[i]; }
}


//
// Function to return ini file window params
//
extern int __stdcall get_win_vals(int *x,int *y,int *width,int *height, SCREENDEF screen[4])
{    int i;
     *x=my_window_x; *y=my_window_y; *width=my_window_width; *height=my_window_height;
     for (i=0;i<4;i++)
         { screen[i].x=Lines[i].x;
           screen[i].y=Lines[i].y;
           strcpy(screen[i].FontName,Lines[i].FontName);
           screen[i].FontType=Lines[i].FontType;
           screen[i].FontHeight=Lines[i].FontHeight;
           screen[i].FontWidth=Lines[i].FontWidth;
           screen[i].r=Lines[i].r;         
           screen[i].g=Lines[i].g;
           screen[i].b=Lines[i].b;           
           screen[i].rb=Lines[i].rb;         
           screen[i].gb=Lines[i].gb;
           screen[i].bb=Lines[i].bb;  
           screen[i].Bold=Lines[i].Bold;         
           screen[i].Underline=Lines[i].Underline;
           screen[i].Italics=Lines[i].Italics; 
           }
}

//================================================================================================================================
// function to read from an configuration file
// currently only looks for debug=0 or 1 to switch debugging off or on
//================================================================================================================================
extern int __stdcall read_cfg_file()
{
     FILE *fp;
     char line[128],fname[256],c[4],str[128];
     int linelen,ln,val,i;
     VLCD_BYTE chars[8];
     
     debug=0;
     fp=fopen("displays\\VirtualLCD.cfg","r");
     if (fp != NULL) 
      {
       while (fgets(line,128,fp))
       {   strcpytonl(line,line);      // remove \n character
           linelen=strlen(line);
           if (linelen>0) 
             { if (line[0]!='/')
                 { if (!strncmp(line,"debug=",6)) { sscanf(&line[6],"%d",&debug); open_mylog(); }
                   else if (!strncmp(line,"X=",2)) sscanf(&line[2],"%d",&my_window_x);
                   else if (!strncmp(line,"Y=",2)) sscanf(&line[2],"%d",&my_window_y);
                   else if (!strncmp(line,"Width=",6)) sscanf(&line[6],"%d",&my_window_width);
                   else if (!strncmp(line,"Height=",7)) sscanf(&line[7],"%d",&my_window_height); 
                   else if (!strncmp(line,"DontShowWindow=",15)) sscanf(&line[15],"%d",&DontShowWindow);  
                   else if (!strncmp(line,"Record=",7)) sscanf(&line[7],"%d",&Record);   
                   else if (!strncmp(line,"RecordFile=",11)) { strcpy(RecordFile,&line[11]); } 
                   else if (!strncmp(line,"RecordInterval=",15)) sscanf(&line[15],"%d",&RecordInterval);          
                   else if (!strncmp(line,"Line",4)) 
                     { c[0]=line[4]; c[1]=0; ln=(atoi(c)-1);
//                       sprintf(str,"%d",ln); mylog("Read cfg - line",str);
                       if (line[5]=='X') 
                         { sscanf(&line[7],"%d",&Lines[ln].x); sprintf(str,"%d",Lines[ln].x); mylog("x=",str); }
                       else if (line[5]=='Y') 
                         { sscanf(&line[7],"%d",&Lines[ln].y); sprintf(str,"%d",Lines[ln].y); mylog("y=",str); }
                       else if (!strncmp(&line[5],"FontType=",9)) sscanf(&line[5+9],"%d",&Lines[ln].FontType);
                       else if (!strncmp(&line[5],"FontHeight=",11)) sscanf(&line[5+11],"%d",&Lines[ln].FontHeight);  
                       else if (!strncmp(&line[5],"FontWidth=",10)) sscanf(&line[5+10],"%d",&Lines[ln].FontWidth);
                       else if (!strncmp(&line[5],"FontColor=",10)) 
                         { sscanf(&line[5+10],"%d %d %d",&Lines[ln].r,&Lines[ln].g,&Lines[ln].b); 
                           sprintf(str,"%d %d %d",Lines[ln].r,Lines[ln].g,Lines[ln].b);
                           mylog("Text Color",str);
                         } 
                       else if (!strncmp(&line[5],"FontBkColor=",12)) 
                         { sscanf(&line[5+12],"%d %d %d",&Lines[ln].rb,&Lines[ln].gb,&Lines[ln].bb);
                           sprintf(str,"%d %d %d",Lines[ln].rb,Lines[ln].gb,Lines[ln].bb);
                           mylog("Text Background Color",str);
                         } 
                       else if (!strncmp(&line[5],"FontBold=",9)) 
                         { sscanf(&line[5+9],"%d",&Lines[ln].Bold); }  
                       else if (!strncmp(&line[5],"FontItalics=",12))
                         { sscanf(&line[5+12],"%d",&val); if (val!=0) val=ITALIC; Lines[ln].Italics=val; }                        
                       else if (!strncmp(&line[5],"FontUnderline=",14))
                         { sscanf(&line[5+14],"%d",&val); if (val!=0) val=ULINE; Lines[ln].Underline=val; }   
                       else if (!strncmp(&line[5],"FontName=",9)) sscanf(&line[5+9],"%d",&Lines[ln].FontName);    
                     }
                   else if (!strncmp(line,"Icon",4))
                     { c[0]=line[4]; c[1]=line[5]; c[2]=0; ln=(atoi(c));
                       if (!strncmp(&line[6],"Filename",8)) { putcharmapfname(ln,&line[15]); }
                       else if (!strncmp(&line[6],"Char",4))
                         { for (i=0;i<8;i++) chars[i]=atoi(&line[11+(i*3)]);    
                           putcharmapchars(ln,chars);
                         }        
                     }  
                   else if (!strncmp(line,"ResetCharMap",12))  
                         { resetcharmap(); }               
                 }
             }
        }
        fclose(fp);
       }
}


extern int __stdcall mylog(char * module, char * msg)
{
   time_t time_since;
   struct tm * cur_time;
   char log_time[20],log_line[120];
   if ((debug!=0) && (log_opened==0)) open_mylog();
   if ((debug!=0) && (log_opened==1))
     { time( &time_since );   // get the time 
       cur_time =localtime( &time_since );  // convert to local time
       strftime(log_time, sizeof log_time, "%H:%M:%S %d/%m/%y", cur_time );  
       fprintf(fp_log,"%s %s %s\n",log_time,module,msg);
       fflush(fp_log);
     }
}


extern int __stdcall open_mylog()
{  // If the log file fails to open there's not much we can do
   if (debug!=0)
     { if (fp_log==NULL)
        {
          if ((fp_log=fopen("displays\\VirtualLCD.log","a"))==NULL) printf("Failed to open ini file");
            else log_opened=1;
          mylog("open_log","VirtualLCD Initialising");
        }
     }
}

extern int __stdcall mylog_error(char *msg)
{ char error_msg[1024],mylastError[1024];

  FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                 NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                 mylastError, 1024, NULL);
  strcpy(error_msg,msg);
  strcat(error_msg," : ");
  strcat(error_msg,mylastError);
  mylog("Error",error_msg);
}

extern int __stdcall close_mylog() { if ((debug!=0) && (log_opened==1)) { fclose(fp_log); log_opened=0; } }

extern int __stdcall mylogi(char * module, char * msg) { mylog(module,msg); return 1; }

extern int __stdcall mylogw(char * module, UINT msg)
{ int i; char str[256];

  sprintf(str,"Unfound code %d",msg);
  for (i=0; i<NUM_WMTAGS; i++)
    { if (msg==wmtags[i].dec) { strcpy(str,wmtags[i].msg); } }
    
  mylog(module,str);
}
